package com.nymph.binding;

import com.nymph.session.SqlSession;

import java.lang.reflect.Proxy;

/**
 * @Description: This is a sample class.
 * @Author: Simon
 */
public class MapperProxyFactory<T> {

    private final Class<T> mapperInterface;

    public MapperProxyFactory(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }

    // 根据SqlSession创建一个代理
    public T newInstance(SqlSession sqlSession) {
        MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, this.mapperInterface);
        return newInstance(mapperProxy);
    }

    // 代理对象保护级别更高
    // 根据mapper代理返回实例
    @SuppressWarnings("unchecked")
    protected T newInstance(MapperProxy<T> mapperProxy) {
        return (T) Proxy.newProxyInstance(this.mapperInterface.getClassLoader(),
                new Class[]{this.mapperInterface}, mapperProxy);
    }

}
